import unittest
from unittest.mock import patch, MagicMock
import click.testing
from tools.cmd.gen import gen
import tempfile

class TestGenCommand(unittest.TestCase):
    """测试gen命令"""
    
    def setUp(self):
        self.runner = click.testing.CliRunner()
    
    def test_gen_help(self):
        """测试gen命令帮助"""
        result = self.runner.invoke(gen, ['--help'])
        self.assertEqual(result.exit_code, 0)
        self.assertIn('Generate a Slice Definition File', result.output)
    
    @patch('tools.cmd.gen.SDFFileGenerator')
    def test_gen_basic_execution(self, mock_generator):
        """测试基本gen命令执行"""
        mock_instance = MagicMock()
        mock_generator.return_value = mock_instance
        
        with tempfile.TemporaryDirectory() as tmpdir:
            result = self.runner.invoke(gen, [
                '-r', '24.03-LTS',
                '-o', tmpdir,
                '-p', 'brotli'
            ])
            
            self.assertEqual(result.exit_code, 0)
            mock_generator.assert_called_once()
            mock_instance.generate.assert_called_once()
    
    def test_gen_missing_package(self):
        """测试缺少包名参数"""
        with tempfile.TemporaryDirectory() as tmpdir:
            result = self.runner.invoke(gen, [
                '-r', '24.03-LTS',
                '-o', tmpdir
                # 缺少 -p 参数
            ])
            self.assertNotEqual(result.exit_code, 0)
    
    def test_gen_invalid_package_name(self):
        """测试无效的包名"""
        with tempfile.TemporaryDirectory() as tmpdir:
            result = self.runner.invoke(gen, [
                '-r', '24.03-LTS',
                '-o', tmpdir,
                '-p', ''  # 空包名
            ])
            self.assertNotEqual(result.exit_code, 0)
    
    @patch('tools.cmd.gen.SDFFileGenerator')
    def test_gen_sdf_creation(self, mock_generator):
        """测试SDF文件创建"""
        mock_instance = MagicMock()
        mock_generator.return_value = mock_instance
        
        with tempfile.TemporaryDirectory() as tmpdir:
            result = self.runner.invoke(gen, [
                '-r', '24.03-LTS',
                '-o', tmpdir,
                '-p', 'python3'
            ])
            
            self.assertEqual(result.exit_code, 0)
            # 验证生成器被正确调用
            mock_generator.assert_called_with(
                package_name='python3',
                release='24.03-LTS',
                output_dir=tmpdir
            )